<template>
  <view class="nurse-edit-container">
    <view class="page-header">
      <text class="page-title">编辑护士</text>
      <text class="page-subtitle">修改护士信息</text>
    </view>

    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <view v-else class="form-container">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="form-label">关联用户</text>
          <view class="info-text">{{ userDisplayName }}</view>
          <text class="form-hint">用户信息不可修改</text>
        </view>

        <view class="form-item">
          <text class="form-label required">职称等级</text>
          <radio-group @change="onTitleLevelChange" class="radio-group">
            <label class="radio-item">
              <radio value="0" :checked="formData.title_level === 0" color="#007aff"/>
              <text class="radio-text">护士</text>
            </label>
            <label class="radio-item">
              <radio value="1" :checked="formData.title_level === 1" color="#007aff"/>
              <text class="radio-text">护师</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.title_level === 2" color="#007aff"/>
              <text class="radio-text">主管护师</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.title_level === 3" color="#007aff"/>
              <text class="radio-text">副主任护师</text>
            </label>
            <label class="radio-item">
              <radio value="4" :checked="formData.title_level === 4" color="#007aff"/>
              <text class="radio-text">主任护师</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label">头像</text>
          <uni-file-picker 
            v-model="photoFileList"
            file-mediatype="image"
            mode="grid"
            :limit="1"
            :auto-upload="false"
            @select="handlePhotoSelect"
            @delete="handlePhotoDelete"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">执业信息</text>
        
        <view class="form-item">
          <text class="form-label">执业证号</text>
          <uni-easyinput 
            v-model="formData.license_no"
            placeholder="请输入护士执业证号"
            :clearable="true"
            trim="all"
            @blur="validateLicenseNo"
          />
          <text class="form-hint">15位数字格式</text>
          <text v-if="errors.license_no" class="error-text">{{ errors.license_no }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">所属科室</text>
          <uni-easyinput 
            v-model="formData.department"
            placeholder="如：口腔科、护理部等"
            :clearable="true"
            trim="all"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">专业背景</text>
        
        <view class="form-item">
          <text class="form-label">教育背景</text>
          <uni-easyinput 
            v-model="formData.education_background"
            placeholder="如：某某大学护理学专业"
            :clearable="true"
            trim="all"
          />
        </view>

        <view class="form-item">
          <text class="form-label">工作年限</text>
          <uni-easyinput 
            v-model="formData.years_experience"
            type="number"
            placeholder="请输入工作年限"
            :clearable="true"
          />
        </view>

        <view class="form-item">
          <text class="form-label">个人简介</text>
          <textarea 
            v-model="formData.introduction" 
            class="form-textarea" 
            placeholder="请输入护士个人简介"
            maxlength="1000"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">工作信息</text>
        
        <view class="form-item">
          <text class="form-label required">工作状态</text>
          <radio-group @change="onWorkingStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="0" :checked="formData.working_status === 0" color="#007aff"/>
              <text class="radio-text">在职</text>
            </label>
            <label class="radio-item">
              <radio value="1" :checked="formData.working_status === 1" color="#007aff"/>
              <text class="radio-text">请假</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.working_status === 2" color="#007aff"/>
              <text class="radio-text">外出</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const pageLoading = ref(true)
const nurseId = ref('')
const photoFileList = ref([])
const originalPhotoUrl = ref('')
const originalPhotoData = ref(null)
const userDisplayName = ref('')

const formData = reactive({
  user_id: '',
  title_level: 0,
  photo: '',
  license_no: '',
  department: '',
  education_background: '',
  years_experience: '',
  introduction: '',
  working_status: 0
})

const errors = reactive({
  license_no: ''
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  nurseId.value = currentPage.options.id || ''
  
  if (!nurseId.value) {
    uni.showToast({ title: '缺少护士ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/nurses/list' })
    }, 1500)
    return
  }
  
  await loadNurseData()
  pageLoading.value = false
})

function getImageUrl(imageData) {
  if (!imageData) return ''
  if (typeof imageData === 'string') return imageData
  if (typeof imageData === 'object' && imageData.url) return imageData.url
  if (Array.isArray(imageData) && imageData.length > 0) {
    const first = imageData[0]
    return typeof first === 'string' ? first : (first.url || '')
  }
  return ''
}

async function loadNurseData() {
  try {
    // 调用云对象方法获取护士信息
    const nursesObj = uniCloud.importObject('dh-nurses')
    const result = await nursesObj.getNurseById(nurseId.value)
    
    if (result.code === 200 && result.data) {
      const data = result.data
      
      // 保存原始照片数据
      if (data.photo) {
        if (typeof data.photo === 'string') {
          originalPhotoData.value = {
            bsonType: 'file',
            fileMediaType: 'image',
            url: data.photo
          }
        } else {
          originalPhotoData.value = data.photo
        }
      } else {
        originalPhotoData.value = null
      }
      
      const photoUrl = getImageUrl(data.photo)
      
      Object.assign(formData, {
        user_id: data.user_id || '',
        title_level: data.title_level !== undefined ? data.title_level : 0,
        photo: photoUrl,
        license_no: data.license_no || '',
        department: data.department || '',
        education_background: data.education_background || '',
        years_experience: data.years_experience?.toString() || '',
        introduction: data.introduction || '',
        working_status: data.working_status !== undefined ? data.working_status : 0
      })
      
      if (photoUrl) {
        originalPhotoUrl.value = photoUrl
        photoFileList.value = [{ url: photoUrl, name: '头像' }]
      }
      
      // 获取用户显示名称（云对象已通过 enrichNurseInfo 处理，返回 nurse_name 字段）
      if (data.nurse_name) {
        userDisplayName.value = data.nurse_name
      } else if (formData.user_id) {
        // 如果云对象没有返回 nurse_name，尝试直接查询用户信息
        try {
          const db = uniCloud.database()
          const userRes = await db.collection('uni-id-users')
            .doc(formData.user_id)
            .field('realname_auth, nickname, username')
            .get()
          if (userRes.data && userRes.data.length > 0) {
            const user = userRes.data[0]
            userDisplayName.value = user.realname_auth?.real_name || 
                                   user.nickname || 
                                   user.username || 
                                   '未知用户'
          } else {
            userDisplayName.value = '未知用户'
          }
        } catch (err) {
          console.error('获取用户信息失败:', err)
          userDisplayName.value = '未知用户'
        }
      } else {
        userDisplayName.value = '未知用户'
      }
    } else {
      throw new Error(result.message || '护士不存在')
    }
  } catch (err) {
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/nurses/list' })
    }, 1500)
  }
}

function onTitleLevelChange(e) {
  formData.title_level = parseInt(e.detail.value)
}

function onWorkingStatusChange(e) {
  formData.working_status = parseInt(e.detail.value)
}

function validateLicenseNo() {
  if (!formData.license_no || formData.license_no.trim().length === 0) {
    errors.license_no = ''
    return
  }
  
  // 验证护士执业证号格式：15位数字
  // 格式：前6位行政区划代码 + 4位年份 + 4位顺序号 + 1位校验码
  const licenseNoPattern = /^\d{15}$/
  if (!licenseNoPattern.test(formData.license_no)) {
    errors.license_no = '护士执业证号格式不正确（应为15位数字）'
  } else {
    errors.license_no = ''
  }
}

function handlePhotoSelect(e) {
  if (e.tempFiles && e.tempFiles.length > 0) {
    photoFileList.value = e.tempFiles
  }
}

function handlePhotoDelete(e) {
  photoFileList.value = []
}

async function uploadPhotoToCloud() {
  if (!photoFileList.value || photoFileList.value.length === 0) {
    return null
  }
  
  try {
    const tempFile = photoFileList.value[0]
    const uploadResult = await uniCloud.uploadFile({
      filePath: tempFile.path,
      cloudPath: `nurses/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${tempFile.name.split('.').pop()}`
    })
    // 返回符合数据库schema的file对象结构
    return {
      name: uploadResult.fileID.split('/').pop(),
      extname: tempFile.name.split('.').pop(),
      url: uploadResult.fileID,
      size: tempFile.size || 0,
      file_id: uploadResult.fileID
    }
  } catch (err) {
    throw err
  }
}

async function handleSubmit() {
  // 如果填写了执业证号，验证格式
  if (formData.license_no && formData.license_no.trim().length > 0) {
    const licenseNoPattern = /^\d{15}$/
    if (!licenseNoPattern.test(formData.license_no)) {
      uni.showToast({ title: '护士执业证号格式不正确（应为15位数字）', icon: 'none' })
      return
    }
  }
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    // 处理照片 - 判断是否有新图片
    let photoData = null
    let hasNewPhoto = false
    
    if (photoFileList.value && photoFileList.value.length > 0) {
      const currentFile = photoFileList.value[0]
      
      // 判断是否是新上传的图片
      if (currentFile.file || 
          (currentFile.url && currentFile.url.startsWith('blob:')) ||
          (currentFile.status === 'ready' && currentFile.path)) {
        hasNewPhoto = true
      }
    }
    
    if (hasNewPhoto) {
      uni.showLoading({ title: '上传照片中...' })
      photoData = await uploadPhotoToCloud()
    } else if (originalPhotoData.value) {
      // 保持原始file对象格式
      photoData = originalPhotoData.value
    }
    
    const db = uniCloud.database()
    const dbCmd = db.command
    
    // 构建提交数据
    const submitData = {
      title_level: formData.title_level,
      license_no: formData.license_no,
      department: formData.department,
      education_background: formData.education_background,
      years_experience: parseInt(formData.years_experience) || 0,
      introduction: formData.introduction,
      working_status: formData.working_status,
      update_time: Date.now()
    }
    
    // 处理照片字段
    if (photoData) {
      submitData.photo = photoData
    } else {
      submitData.photo = dbCmd.remove()
    }
    
    // 调用云对象方法更新护士信息
    const nursesObj = uniCloud.importObject('dh-nurses')
    const result = await nursesObj.updateNurse(nurseId.value, submitData)
    
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: result.message || '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/nurses/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '更新失败', icon: 'none' })
    }
  } catch (err) {
    uni.hideLoading()
    uni.showToast({ title: err.message || '更新失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/nurses/list' })
}
</script>

<style lang="scss" scoped>
.nurse-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  background: #fff;
  border-radius: 16rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.info-text {
  font-size: 28rpx;
  color: #333;
  padding: 20rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
}

.form-hint {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-top: 8rpx;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
